package com.tedu.util;


import com.mysql.cj.jdbc.Driver;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * Author：毕龙
 * Date: 2024/6/14 15:04
 */
public class JDBCUtil {

    //获取数据
    private static Properties properties = new Properties();


    static {
        //读取配置文件的信息
        InputStream is = null;
        try {
            //获取配置文件的信息将该信息存入到缓冲流中
            is = JDBCUtil.class.getClassLoader().getResourceAsStream("config/jdbc.properties");
            //将流中的数据转入的properties
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


    //获取链接
    public static Connection getConnection() {
        //通过properties的键获取properties属性中的值
        String driver = properties.getProperty("com.tedu.driver");
        String url = properties.getProperty("com.tedu.url");
        String username = properties.getProperty("com.tedu.username");
        String password = properties.getProperty("com.tedu.password");
        //1.加载驱动
        Connection conn = null;
        try {
            Class.forName(driver);
            //2.获取链接
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return conn;
    }

    //资源释放
    public static void release(ResultSet rs, PreparedStatement pstm, Connection conn){
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if (pstm != null) {
            try {
                pstm.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if(conn != null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

}
